/*
 * 创建日期 2010-1-2
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.grid.util;

import  org.fantasy.common.db.bean.Cell;
import  org.fantasy.common.db.bean.ReportCell;
import  org.fantasy.common.db.bean.ReportRow;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;

/**
 * 数据转换工具
 * @author: 王文成
 * @version: 1.0
 * @since 2010-1-2
 */
public class GridUtil {

    /**
     * 将查询结果转换成Report
     * 
     * @param dynaList
     * @return
     */
    public static List<ReportRow> dynaBeanList2Report(List<DynaBean> dynaList) {
        if (dynaList.isEmpty())
            return new ArrayList<ReportRow>(0);
        DynaBean dynaBean = dynaList.get(0);
        DynaProperty[] props = dynaBean.getDynaClass().getDynaProperties();
        List<ReportRow> rows = new ArrayList<ReportRow>(dynaList.size());
        ReportRow preRow = null;
        for (DynaBean bean : dynaList) {
            ReportRow row = new ReportRow();
            ReportCell preCell = null;
            for (int i = 0; i < props.length; i++) {
                DynaProperty p = props[i];
                ReportCell cell = new ReportCell();
                cell.setColClass(p.getType());
                cell.setValue(bean.get(p.getName()));
                cell.setName(p.getName());
                row.put(p.getName(), cell);
                linkX(preCell, cell);
                preCell = cell;
            }
            rows.add(row);
            linkY(preRow, row);
            preRow = row;
        }
        return rows;
    }

    /**
     * 横向链接
     * 
     * @param preCell
     * @param cell
     */
    private static void linkX(ReportCell preCell, ReportCell cell) {
        if (preCell != null) {
            preCell.setXNext(cell);
            cell.setXPrevious(preCell);
        }
    }

    /**
     * 纵向链接
     * 
     * @param preRow
     * @param row
     */
    private static void linkY(ReportRow preRow, ReportRow row) {
        if (preRow != null) {
            List<Cell> cells = row.cells();
            for (int i = 0; i < cells.size(); i++) {
                ReportCell cell = (ReportCell) cells.get(i);
                ReportCell preCell = (ReportCell) preRow.getCell(cell.getName());
                cell.setYPrevious(preCell);
                preCell.setYNext(cell);
            }
        }
    }
}
